define(['mui', 'ajax', 'jquery', 'swiper', 'dropload', 'app'], function() {
	mui.init({
		keyEventBind: {
			backbutton: false //关闭back按键监听
		}
	});

	var picListTpl = document.getElementById('newsPicListTpl').innerHTML; //图片轮播模板
	var artListTpl = document.getElementById('newsArticleListTpl').innerHTML; //新闻列表模板
	var minHeight = document.body.scrollHeight;
	console.log(minHeight)
	$('.pullrefresh').height(minHeight) - 40;
	var currentData = getNowFormatDate();

	function loadListCallback(tNews) {
		//addIsNewtender(tNews.info);
		if(tNews.code === statusCode.ERROR) {
			return false;
		} else if(tNews.code === statusCode.SUCCESS) {
			laytpl(artListTpl).render(tNews.info, function(h) {
				$('.ul_news_list_common').html(h);
			});
		}
		tNews = null;
		curDiv = null;
		$('.pullrefresh').scrollTop(0);
	}

	function loadImgCallback(tPic, curDiv) {
		addThumbImageWith(tPic.info);
		if(tPic.code === statusCode.ERROR) {
			return false;
		} else if(tPic.code === statusCode.SUCCESS) {
			//把数据加入到轮播模板在把数据加入到轮播区域<div class="div_pics_region"></div>
			laytpl(picListTpl).render(tPic.info, function(h) {
				//console.log(h)
				$('.swiper-wrapper').html(h);
			});

		}
	}

	function loadMoreList(tNews, page) {
		console.log("loadMoreList")
		//addIsNewtender(tNews.info);
		if(tNews.code === statusCode.ERROR) {
			return false;
		} else if(tNews.code === statusCode.SUCCESS) {
			laytpl(artListTpl).render(tNews.info, function(h) {
				$('.ul_news_list_common').append(h);
				$('.hidden_curPage').val(page);
			});
		}
	}
	//上拉刷新增加数据
	function addArcList() {

		var gtime = $.trim($('.hidden_gtime').val()); //获取时间
		var page = $('.hidden_curPage').val(); //获取page数如1或者2什么的
		page++; //page自增
		var tNews = getNewsListInfo(ajax_SearchURL, currentData, page, loadMoreList, page); //下拉刷新获取更多数据，主要是传递page自增的数据和时间戳
	};

	$(function() {
		$('.pullrefresh').scroll(function() {
			//console.log('pullrefresh')
			$('.swiper-container-h').height('auto');
			addArcList(); //下滑时更具距离自动加载数据
		});
		//dropload移动端下拉刷新、上拉加载更多插件 https://github.com/ximan/dropload
		$('.pullrefresh').dropload({
			scrollArea: $('.pullrefresh'),
			domUp: {
				domClass: 'dropload-up',
				domRefresh: '<div class="dropload-refresh">↓下拉刷新</div>',
				domUpdate: '<div class="dropload-update">↑释放更新</div>',
				domLoad: '<div class="dropload-load"><span class="loading"></span>加载中...</div>'
			},
			domDown: {
				domClass: 'dropload-down',
				domRefresh: '<div class="dropload-refresh"></div>',
				domLoad: '<div class="dropload-load"><span class="loading"></span>加载中...</div>',
				domNoData: '<div class="dropload-noData">暂无数据</div>'
			},
			loadUpFn: function(me) {
				refreshHtml(true, false);
				me.resetload(); // 每次数据加载完，必须重置
			},
			loadDownFn: function(me) {
				me.resetload(); // 每次数据加载完，必须重置
			}
		});

	});
	// oType = 1 判断是否刷新  否则强制刷新
	function refreshHtml(oType, isfirst) {
		if(isfirst) {
			getImgNewsByCid(ajax_indexSlideURL, currentData, loadImgCallback);
		}
		getNewsListInfo(ajax_SearchURL, currentData, 1, loadListCallback);
		return true;
	}

	function getNewsListInfo(url, atime, Pageindex, loadListCallback, page) {
		var me = new Object();
		var user = null,
			token = '';
		user = judgeLogin();
		if(user) {
			token = user.token;
		} else {
			token = '';
		}
		var data_form = {
			transtime: atime,
			keyword: "",
			AreaID: "",
			Pageindex: Pageindex,
			Type: 0,
			token: token
		};
		mui.ajax({
			type: "POST",
			url: url,
			async: true,
			data: data_form,
			dataType: "json",
			success: function(data_) {
				//              	console.log(url)
				//              	console.log(JSON.stringify(data_form))
				console.log(data_)
				data = JSON.parse(data_);
				if(data.result == 1 && data.SearchResult.length != 0) {
					me.code = statusCode.SUCCESS;
					me.info = data.SearchResult;
				} else {
					me.code = statusCode.NODATA;
					plus.nativeUI.toast("没有更多数据了")
				}
				loadListCallback(me, page)
			},
			error: function() {
				plus.nativeUI.toast("网络超时")
				plus.nativeUI.closeWaiting();
				me.code = statusCode.ERROR;
			}
		});

		//return me.getResult();
	}

	function getImgNewsByCid(url, params, callback) {
		var me = new Object();
		try {
			mui.ajax({
				type: "POST",
				data: {
					transtime: params
				},
				async: false,
				url: url,
				dataType: "json",
				success: function(data_) {
					data = JSON.parse(data_);
					console.log('111:', data_);
					if(data.result == 1) {
						me.code = statusCode.SUCCESS;
						me.info = data.Slide;
					} else {
						me.code = statusCode.NODATA;
					}
					callback(me)
				},
				error: function() {
					me.code = statusCode.ERROR;
				}
			});
		} catch(e) {
			me.code = statusCode.ERROR;
		}
	}
	//增加轮播图地址
	function addThumbImageWith(data) {
		console.log('%o', data.length);
		for(var i = 0, len = data.length; i < len; i++) {
			data[i].thumb = main_host + data[i].ImgURL;
			console.log(data[i].thumb)
		}
		return data;
	}
	//+---------------------------------------------------  
	//| 求两个时间的天数差 日期格式为 YYYY-MM-dd   
	//+---------------------------------------------------  
	function daysBetween(DateOne, DateTwo) {
		var OneMonth = DateOne.substring(5, DateOne.lastIndexOf('-'));
		var OneDay = DateOne.substring(DateOne.length, DateOne.lastIndexOf('-') + 1);
		var OneYear = DateOne.substring(0, DateOne.indexOf('-'));

		var TwoMonth = DateTwo.substring(5, DateTwo.lastIndexOf('-'));
		var TwoDay = DateTwo.substring(DateTwo.length, DateTwo.lastIndexOf('-') + 1);
		var TwoYear = DateTwo.substring(0, DateTwo.indexOf('-'));

		var cha = ((Date.parse(OneMonth + '/' + OneDay + '/' + OneYear) - Date.parse(TwoMonth + '/' + TwoDay + '/' + TwoYear)) / 86400000);
		OneMonth = null, OneDay = null, OneYear = null, TwoMonth = null, TwoDay = null, TwoYear = null;
		return Math.abs(cha);
	}

	var galleryTop = null,
		galleryThumbs = null;

	mui.plusReady(function() {
		refreshHtml(true, true);
		galleryThumbs = new Swiper('.swiper-container-h', {
			//		  	pagination: '.swiper-pagination-h',
			preloadImages: true,
			// Enable lazy loading
			lazyLoading: true,
			threshold: 0,
			autoplay: 5000,
			autoplayDisableOnInteraction : false,
			loop : true
		});
		var transtime = getNowFormatDate();
		var url = ajax_articleDetailURL;

		//设置更新new状态的代理函数
		window.addEventListener('updateStatus', function(event) {
			//通过event.detail可获得传递过来的参数内容
			var id = event.detail.id;
			$("#" + id + " span#newMessage").hide()
		});

		//点击轮播图
		mui('.div_pics_region ').on('tap', '.swiper-slide', function() {
			if(unsafe_tap()) return; //防御编码
			var channelID = this.children[0].getAttribute('article-type');
			var articleID = this.children[0].getAttribute('data-id');
			var user = judgeLogin();

			if(user) {
				mui.openWindow({
					id: 'base_page.html',
					url: 'base_page.html',
					styles: {
						top: 0,
						bottom: 0,
						bounce: 'none',
						popGesture: 'close'
					},
					extras: {
						pageurl: url,
						usertoken: user.token,
						transtime: transtime,
						pagechannelid: channelID,
						pagearticleid: articleID,
						atitle: '资讯信息',
					},
					waiting: {
						autoShow: false,
					},
					createNew: false, //是否重复创建同样id的webview，默认为false:不重复创建，直接显示
				});
			} else {
				plus.nativeUI.toast("请登录");
				openpage('login_standard.html');
			}
			user = null, channelID = null, articleID = null;
		});
	});
})